﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using ESF.General.ClickOnce;
using ESF.General.MVP;

#endregion


namespace ESF.SFT.FileUploader.Presenter.General
{
	public class InternetConnectionOptionsPresenter : BasePresenter<IInternetConnectionOptionsViewer>
	{
		#region Constantes

		private const string EXTERNALTESTWEBURL = "http://www.google.com";

		#endregion


		#region Constructor

		public InternetConnectionOptionsPresenter (IInternetConnectionOptionsViewer pViewer)
		{
			_Viewer = pViewer;
		}

		#endregion


		#region Metodos

		public override void Load ()
		{
			DetectProxySettings ();
		}


		private bool DetectProxySettings ()
		{
			Uri proxyWeb;


			_Viewer.ProxyAddress = string.Empty;
			_Viewer.ProxyPortNumber = string.Empty;

			try
			{
				// Hay proxy!
				if (WebRequest.DefaultWebProxy != null && !WebRequest.DefaultWebProxy.IsBypassed(new Uri(EXTERNALTESTWEBURL)))
				{
					proxyWeb = WebRequest.DefaultWebProxy.GetProxy(new Uri(EXTERNALTESTWEBURL));

					_Viewer.ProxyAddress = proxyWeb.Host;
					_Viewer.ProxyPortNumber = proxyWeb.Port.ToString();

					return true;
				}
			}
			catch (Exception pEx)
			{
				LogError(pEx);
			}

			return false;
		}


		public bool TryConnect()
		{
			HttpWebRequest request;

			CustomClickOnceWebProxy cusProxy;

			try
			{
				DetectProxySettings ();

				if (_Viewer.ProxyAddress.Length > 0)
				{
					request = (HttpWebRequest)WebRequest.Create(EXTERNALTESTWEBURL);

					cusProxy = new CustomClickOnceWebProxy(_Viewer.ProxyAddress, int.Parse(_Viewer.ProxyPortNumber));
					cusProxy.SetCredentials(new NetworkCredential(_Viewer.ProxyUserLogin, _Viewer.ProxyUserPassword));

					WebRequest.DefaultWebProxy = cusProxy;

					request.GetResponse();
				}

				return true;
			}
			catch (Exception pEx)
			{
				LogError(pEx);
			}

			return false;
		}

		#endregion
	}
}
